package com.mission.schedule.activity

import android.app.Activity
import android.appwidget.AppWidgetManager
import android.content.Intent
import android.graphics.Bitmap
import android.os.Bundle
import android.os.Handler
import android.os.Message
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.TextUtils
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.Toast
import com.android.volley.*
import com.android.volley.toolbox.StringRequest
import com.google.gson.Gson
import com.google.gson.JsonSyntaxException
import com.lidroid.xutils.HttpUtils
import com.lidroid.xutils.exception.HttpException
import com.lidroid.xutils.http.RequestParams
import com.lidroid.xutils.http.ResponseInfo
import com.lidroid.xutils.http.callback.RequestCallBack
import com.lidroid.xutils.http.client.HttpRequest
import com.mission.schedule.R
import com.mission.schedule.add603.bean.UpNew
import com.mission.schedule.applcation.App
import com.mission.schedule.bean.*
import com.mission.schedule.clock.QueryAlarmData
import com.mission.schedule.constants.ShareFile
import com.mission.schedule.constants.URLConstants
import com.mission.schedule.entity.ScheduleTable
import com.mission.schedule.service.NoteShareService
import com.mission.schedule.utils.DateUtil
import com.mission.schedule.utils.ProgressUtil
import com.mission.schedule.utils.SharedPrefUtil
import com.mission.schedule.utils.UriUtils
import com.nostra13.universalimageloader.core.DisplayImageOptions
import com.nostra13.universalimageloader.core.ImageLoader
import com.nostra13.universalimageloader.core.display.FadeInBitmapDisplayer
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener
import kotlinx.android.synthetic.main.activity_selection_firend.*
import kotlinx.android.synthetic.main.adapter_share_url_friends.view.*
import org.json.JSONArray
import org.json.JSONException
import org.json.JSONObject
import java.util.*

/**
 * Created by liwei on 2017/12/26.
 */

class SelectionFirendActivity : Activity() {

    var itemsBeanList: MutableList<NewFriendsActivity.newFriendBean.PageBean.ItemsBean> = arrayListOf()
    lateinit var share: SharedPrefUtil
    var userId = ""
    var name = ""
    var adapter = Adapter()

    lateinit var imageLoader: ImageLoader
    lateinit var animateFirstListener: ImageLoadingListener
    lateinit var options: DisplayImageOptions

    var select = mutableMapOf<Int, Boolean>()
    var select_name = mutableMapOf<Int, String>()

    var dlistbean = DownNewSixTaskBean.ListBean()
    var uftask = UserFrendsTask()
    var clistbean = ClenderUrlBean.ListBean()
    var schSourceType = "5"
    var updateState = "1"
    var schRemark1 = ""
    var schID = "0"
    var map = mapOf<String, String>()
    var titleid = ""
    var titles = ""
    var remark5 = "0"
    var remark6 = "0"
    lateinit var repeatBean: RepeatBean
    var schRemark2 = ""
    var schRemark3 = ""

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_selection_firend)

        schSourceType = intent.getStringExtra("schSourceType")
        schRemark1 = intent.getStringExtra("schRemark1")
        updateState = intent.getStringExtra("updateState")
        schID = intent.getStringExtra("schID")
        titleid = intent.getStringExtra("titleid")
        titles = intent.getStringExtra("titles")
        remark6 = intent.getStringExtra("remark6")
        remark5 = intent.getStringExtra("remark5")
        share = SharedPrefUtil(this@SelectionFirendActivity, ShareFile.USERFILE)
        userId = share.getString(ShareFile.USERID, "")
        name = share.getString(ShareFile.USERNAME, "")
        when (schSourceType) {
            "2", "5" -> clistbean = intent.getSerializableExtra("bean") as ClenderUrlBean.ListBean
            "3", "4" -> dlistbean = intent.getSerializableExtra("bean") as DownNewSixTaskBean.ListBean
            "99" -> {
                map = App.getDBcApplication().querayOneCalenderData(schID.toInt())
                upLoadData()
            }
            "100" -> uftask = intent.getSerializableExtra("bean") as UserFrendsTask
            "0" -> {
                ok_num.visibility = View.GONE
            }
            "repeatBean" -> repeatBean = intent.getSerializableExtra("bean") as RepeatBean
        }



        imageLoader = ImageLoader.getInstance()
        animateFirstListener = AnimateFirstDisplayListener()

        options = DisplayImageOptions.Builder()
                .showStubImage(R.mipmap.b1)
                .showImageForEmptyUri(R.mipmap.b1)
                .showImageOnFail(R.mipmap.b1).cacheInMemory(true)
                .cacheOnDisc(true).cacheInMemory(true)
                .bitmapConfig(Bitmap.Config.RGB_565) // 设置图片的解码类型
                .build()

        share = SharedPrefUtil(this@SelectionFirendActivity, ShareFile.USERFILE)
        itemsBeanList = App.getDBcApplication().getAllNewFriendData(userId, false)

        recyclerview.layoutManager = LinearLayoutManager(this@SelectionFirendActivity)
        recyclerview.adapter = adapter

        top_ll_back.setOnClickListener {
            onBackPressed()
        }

        ok_num.setOnClickListener {
            if (select.isNotEmpty()) {
                if (schSourceType == "100") {
                    synData(uftask)
                } else {
                    var json = when (schSourceType) {
                        "2", "5" -> Json5()
                        "99" -> JsonMap()
                        else -> Json34()
                    }
                    loadData(json)
                }
                if (schSourceType == "repeatBean") {
                    select.mapKeys {
                        synDataRepeat(it.key, select_name[it.key])
                    }
                    Toast.makeText(this@SelectionFirendActivity, "已转发", Toast.LENGTH_SHORT).show()
                } else {
                    val ar = JSONArray()
                    select.mapKeys {
                        var d = JSONObject()
                        d.put("uid", it.key)
                        d.put("name", name)
                        d.put("mess", "@${name}给你发了一条链接")
                        d.put("pushType", 9)
                        ar.put(d)
                    }
                    pushIphoneOrAndroid(ar.toString())
                }
            } else {
                Toast.makeText(this@SelectionFirendActivity, "请选择分享好友", Toast.LENGTH_SHORT).show()
            }
        }
    }

    private fun loadData(json: String) {
        var loaders = ProgressUtil()
        loaders.ShowProgress(this@SelectionFirendActivity, true, true, "正在分享...")
        val request3 = object : StringRequest(Method.POST, URLConstants.同步临时表数据, Response.Listener { s ->
            if (!TextUtils.isEmpty(s)) {
                try {
                    val goon = Gson()
                    val bean = goon.fromJson(s, NewShareBean::class.java)
                    if (bean.status == 0) {
                        if (schSourceType == "2" || schSourceType == "99") {
                            map = App.getDBcApplication().querayOneCalenderData(schID.toInt())
                            App.getDBcApplication().updateSchRemark1(schID, schRemark2, schRemark3, map[ScheduleTable.schRemark5])
                        }
                        onBackPressed()
                        Toast.makeText(this@SelectionFirendActivity, "分享成功", Toast.LENGTH_SHORT).show()
                    }
                } catch (e: JsonSyntaxException) {
                    e.printStackTrace()
                }
            }
            loaders.dismiss()
        }, Response.ErrorListener {
            loaders.dismiss()
        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map["data"] = json
                return map
            }
        }
        request3.tag = "同步临时表数据"
        request3.retryPolicy = DefaultRetryPolicy(5000, 1, 1.0f)
        App.getHttpQueues().add(request3)
    }

    private fun pushIphoneOrAndroid(arr: String) {
        val request3 = object : StringRequest(Method.POST, URLConstants.本地添加推送信息, Response.Listener { _ ->
        }, Response.ErrorListener {
        }) {
            @Throws(AuthFailureError::class)
            override fun getParams(): Map<String, String> {
                val map = HashMap<String, String>()
                map.put("data", "{\"timetable\":$arr}")
                return map
            }
        }
        request3.tag = "本地添加推送信息"
        request3.retryPolicy = DefaultRetryPolicy(5000, 1, 1.0f)
        App.getHttpQueues().add(request3)
    }

    internal var handler: Handler = object : Handler() {
        override fun handleMessage(msg: Message?) {
            super.handleMessage(msg)
            ok_num.text = "确认${if (select.isNotEmpty()) "(${select.size})" else ""}"
        }
    }


    inner class Adapter : RecyclerView.Adapter<Adapter.Holder>() {
        override fun getItemCount(): Int {
            return itemsBeanList.size
        }

        override fun onBindViewHolder(holder: Adapter.Holder, position: Int) {
            if (itemsBeanList.size > 0) {
                if (itemsBeanList[position].pname == null) {
                    holder.itemView.friendname_tv.text = "@无名称"
                } else {
                    holder.itemView.friendname_tv.text = "@" + itemsBeanList[position].pname
                }
                holder.itemView.friendtag_tv.text = "暂无消息!"
                var imageUrl = ""
                if (!itemsBeanList[position].pimgs.isEmpty()) {
                    imageUrl = itemsBeanList[position].pimgs.toString()
                }
                val imagery = URLConstants.图片 + imageUrl + "&imageType=2&imageSizeType=3"
                imageLoader.displayImage(imagery, holder.itemView.friend_img, options,
                        animateFirstListener)
                holder.itemView.select_cb.isChecked = select[itemsBeanList[position].puid] ?: false
                holder.itemView.select_cb.setOnClickListener {
                    if (holder.itemView.select_cb.isChecked) {
                        select[itemsBeanList[position].puid] = true
                        select_name[itemsBeanList[position].puid] = itemsBeanList[position].pname
                    } else {
                        select.remove(itemsBeanList[position].puid)
                        select_name.remove(itemsBeanList[position].puid)
                    }
                    notifyItemChanged(position, 1)
                    val me = Message()
                    handler.sendMessage(me)
                }

                if (schSourceType == "0") {
                    holder.itemView.select_cb.visibility = View.GONE
                    holder.itemView.setOnClickListener {
                        val intentnewf = Intent(this@SelectionFirendActivity, NoteShareService::class.java)
                        intentnewf.action = "noteshare"
                        intentnewf.putExtra("maxTitleId", titleid)
                        intentnewf.putExtra("titles", titles)
                        intentnewf.putExtra("remark5", remark5)
                        intentnewf.putExtra("remark6", remark6)
                        intentnewf.putExtra("uid", itemsBeanList[position].puid)
                        startService(intentnewf)
                        Toast.makeText(this@SelectionFirendActivity, "已发送！", Toast.LENGTH_SHORT).show()
                    }
                }
            }
        }

        override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): Adapter.Holder {
            val view = LayoutInflater.from(this@SelectionFirendActivity).inflate(R.layout.adapter_share_url_friends, parent, false)
            return Holder(view)
        }

        inner class Holder(view: View) : RecyclerView.ViewHolder(view)

    }

    private class AnimateFirstDisplayListener : SimpleImageLoadingListener() {

        override fun onLoadingComplete(imageUri: String, view: View?,
                                       loadedImage: Bitmap?) {
            if (loadedImage != null) {
                val imageView = view as ImageView?
                // 是否第一次显示
                val firstDisplay = !displayedImages.contains(imageUri)
                if (firstDisplay) {
                    // 图片淡入效果
                    FadeInBitmapDisplayer.animate(imageView, 500)
                    displayedImages.add(imageUri)
                }
            }
        }

        companion object {

            internal val displayedImages: MutableList<String> = Collections.synchronizedList(LinkedList())
        }
    }


    //remark1： 0、日程链接 ；1、任务链接； 2、清单链接；souretype = 0
    private fun JsonMap(): String {
        var data = JSONObject()
        var timetable = JSONArray()
        var index = 0
        select.mapKeys {
            var json = JSONObject()
            json.put("updateState", updateState)
            json.put("uid", it.key)
            json.put("puid", userId)
            json.put("pname", share.getString(ShareFile.USERNAME, ""))
            json.put("ptitleimg", map[ScheduleTable.schImagePath])
            json.put("titleId", map[ScheduleTable.schSourceDesc])
            json.put("cdate", map[ScheduleTable.schDate])
            json.put("ctime", map[ScheduleTable.schTime])
            json.put("content", map[ScheduleTable.schContent])
            json.put("cisEnd", map[ScheduleTable.schIsEnd])
            json.put("cdisplayAlarm", map[ScheduleTable.schDisplayTime])
            json.put("cisAlarm", map[ScheduleTable.schIsAlarm])
            json.put("cbefortime", map[ScheduleTable.schBeforeTime])
            json.put("calarmsound", map[ScheduleTable.schRingCode])
            json.put("calarmsoundDesc", map[ScheduleTable.schRingDesc])
            json.put("cpostpone", map[ScheduleTable.schIsPostpone])
            json.put("cimportant", map[ScheduleTable.schIsImportant])
            json.put("cscore", "0")
            json.put("changeTime", DateUtil.nowTime())
            json.put("createTime", DateUtil.nowTime())
            json.put("remark", "")
            json.put("remark1", "0")
            if (index == 0) {
                json.put("remark2", it.key)
                json.put("remark3", select_name[it.key])
                schRemark2 = it.key.toString()
                schRemark3 = select_name[it.key]!!
            } else {
                json.put("remark2", "")
                json.put("remark3", "")
            }
            var url = map[ScheduleTable.schWebURL]
            val bean = App.getDBcApplication().get_tb_function_my(map[ScheduleTable.schRemark6])
            if (bean != null && !bean.url.isEmpty()) {
                url = bean.url
            } else if (map[ScheduleTable.schContent]!!.length > 2 && map[ScheduleTable.schContent]!!.substring(0, 2) == "#%") {
                val list = App.getDBcApplication().getCalenderNoteDetailData(userId, map[ScheduleTable.schSourceDesc], false)
                if (list.size >= 1 && UriUtils.isUrl(list[0].contents)) {
                    url = list[0].contents
                }
            }
            json.put("remark4", map[ScheduleTable.schRemark6])
            json.put("remark5", url)
            index++
            timetable.put(json)
        }
        data.put("timetable", timetable)


        return data.toString()
    }


    private fun Json5(): String {
        var data = JSONObject()
        var timetable = JSONArray()
        var index = 0
        select.mapKeys {
            var json = JSONObject()
            json.put("updateState", updateState)
            json.put("uid", it.key)
            json.put("puid", if (clistbean.cRecommendId == 0) userId else clistbean.cRecommendId)
            json.put("pname", if (clistbean.cRecommendName.isEmpty()) share.getString(ShareFile.USERNAME, "") else clistbean.cRecommendName)
            json.put("ptitleimg", clistbean.imgPath)
            json.put("titleId", clistbean.cTypeDesc)
            json.put("cdate", clistbean.cDate)
            json.put("ctime", clistbean.cTime)
            json.put("content", clistbean.cContent)
            json.put("cisEnd", clistbean.cIsEnd)
            json.put("cdisplayAlarm", clistbean.cDisplayAlarm)
            json.put("cisAlarm", clistbean.cIsAlarm)
            json.put("cbefortime", clistbean.cBeforTime)
            json.put("calarmsound", clistbean.cAlarmSound)
            json.put("calarmsoundDesc", clistbean.cAlarmSoundDesc)
            json.put("cpostpone", clistbean.cPostpone)
            json.put("cimportant", clistbean.cImportant)
            json.put("cscore", "0")
            json.put("changeTime", DateUtil.nowTime())
            json.put("createTime", DateUtil.nowTime())
            json.put("remark", "")
            json.put("remark1", "0")
            json.put("remark4", "")
            json.put("remark5", "")
            if (index == 0) {
                json.put("remark2", it.key)
                json.put("remark3", select_name[it.key])
                schRemark2 = it.key.toString()
                schRemark3 = select_name[it.key]!!
            } else {
                json.put("remark2", "")
                json.put("remark3", "")
            }
            index++
            timetable.put(json)
        }
        data.put("timetable", timetable)


        return data.toString()
    }

    private fun Json34(): String {
        var data = JSONObject()
        var timetable = JSONArray()
        var index = 0
        select.mapKeys {
            var json = JSONObject()
            json.put("updateState", updateState)
            json.put("uid", it.key)
            json.put("puid", if (dlistbean.puId == 0) userId else dlistbean.puId)
            json.put("pname", dlistbean.pname)
            json.put("ptitleimg", dlistbean.titleImg)
            json.put("titleId", dlistbean.titleId)
            json.put("cdate", dlistbean.cdate)
            json.put("ctime", dlistbean.ctime)
            json.put("content", dlistbean.content)
            json.put("cisEnd", dlistbean.cisEnd)
            json.put("cdisplayAlarm", dlistbean.cdisplayAlarm)
            json.put("cisAlarm", dlistbean.cisAlarm)
            json.put("cbefortime", dlistbean.cbeforTime)
            json.put("calarmsound", dlistbean.calarmSound)
            json.put("calarmsoundDesc", dlistbean.calarmSoundDesc)
            json.put("cpostpone", dlistbean.cpostpone)
            json.put("cimportant", dlistbean.cimportant)
            json.put("cscore", "")
            json.put("changeTime", DateUtil.nowTime())
            json.put("createTime", DateUtil.nowTime())
            json.put("remark", "")
            json.put("remark1", "1")
            json.put("remark4", "")
            json.put("remark5", "")
            if (index == 0) {
                json.put("remark2", it.key)
                json.put("remark3", select_name[it.key])
                schRemark2 = it.key.toString()
                schRemark3 = select_name[it.key]!!
            } else {
                json.put("remark2", "")
                json.put("remark3", "")
            }
            index++
            timetable.put(json)
        }
        data.put("timetable", timetable)


        return data.toString()
    }

    private fun synData(bean: UserFrendsTask) {
        var loaders = ProgressUtil()
        loaders.ShowProgress(this@SelectionFirendActivity, true, true, "正在分享...")
        val data = JSONObject()
        val data1 = JSONObject()
        val array = JSONArray()
        val array1 = JSONArray()
        select.mapKeys {

            val repid = App.getDBcApplication().sendRepeatNoteMinId - 1
            App.getDBcApplication().insertSendRepeatNoteTableData(repid,
                    userId.toInt(), 1, 0, it.key, bean.pDeleState, bean.repInSTable, bean.repType, bean.cBeforTime,
                    bean.cDisplayAlarm, bean.cPostpone, 0, bean.pIsEnd, bean.cIsEnd, bean.styles, bean.cIsDown, bean.cColorType,
                    share.getString(ShareFile.USERNAME, ""), select_name[it.key], share.getString(ShareFile.USERPHOTOPATH, ""),
                    bean.content, "", bean.ctime, "", bean.cIsAlarm, bean.cAlarmSound, bean.cAlarmSoundDesc, bean.createTime,
                    DateUtil.formatDateTime(Date()), bean.titleId, "", bean.remark1, bean.remark2, "", "", "", "")

            try {
                val bean = App.getDBcApplication().getOneSendRepeatNoteData(userId, it.key, bean.titleId, true)
                val beans = App.getDBcApplication().getSendRepeatNoteDetailData(userId, bean.titleId, true)
                val task = JSONObject()

                task.put("id", bean.id)
                task.put("uid", bean.uId)
                task.put("ctype", bean.ctype)
                task.put("uname", bean.uname)
                task.put("pname", bean.pname)
                task.put("ptype", bean.ptype)
                task.put("titleImg", bean.titleImg)
                task.put("puId", bean.puId)
                task.put("pdeleState", 0)
                task.put("content", bean.content)
                task.put("cdate", bean.cdate)
                task.put("ctime", bean.ctime)
                task.put("repInStable", bean.repInSTable)
                task.put("repType", bean.repType)
                task.put("repTypeParameter", bean.repTypeParameter)
                task.put("cisAlarm", bean.cIsAlarm)
                task.put("cbeforTime", bean.cBeforTime)
                task.put("calarmSound", bean.cAlarmSound)
                task.put("calarmSoundDesc", bean.cAlarmSoundDesc)
                task.put("cdisplayAlarm", bean.cDisplayAlarm)
                task.put("cpostpone", bean.cPostpone)
                task.put("cimportant", bean.cImportant)
                task.put("cisEnd", 0)
                task.put("pIsEnd", bean.pIsEnd)
                task.put("styles", bean.styles)
                task.put("cisDown", 0)
                task.put("ccolorType", bean.cColorType)
                task.put("createTime", bean.createTime)
                task.put("changTime", bean.changTime)
                task.put("titleId", bean.titleId)
                task.put("remark", bean.remark)
                task.put("remark1", bean.remark1)
                task.put("remark2", 0)
                task.put("remark3", bean.remark3)
                task.put("remark4", bean.remark4)
                task.put("remark5", bean.remark5)
                task.put("remark6", bean.remark6)
                task.put("updateState", App.getDBcApplication().getOneSendRepeatNoteUpdatestate(userId, it.key, bean.titleId, true))
                array.put(task)

                for (be in beans) {
                    val tasks = JSONObject()
                    tasks.put("id", be.id)
                    tasks.put("uid", be.uId)
                    tasks.put("puId", be.puId)
                    tasks.put("ctype", be.ctype)
                    tasks.put("titleId", be.titleId)
                    tasks.put("titles", be.titles)
                    tasks.put("contents", be.contents)
                    tasks.put("changeTime", be.changeTime)
                    tasks.put("orderId", be.orderId)
                    tasks.put("imgPath", be.imgPath)
                    tasks.put("imgUrl", be.imgUrl)
                    tasks.put("createTime", be.createTime)
                    tasks.put("ltype", be.lType)
                    tasks.put("style", be.style)
                    tasks.put("endstate", be.endstate)
                    tasks.put("nums", be.nums)
                    tasks.put("cpath", be.cpath)
                    tasks.put("curl", be.curl)
                    tasks.put("shareUrl", be.shareUrl)
                    tasks.put("sdesc", be.sdesc)
                    tasks.put("localIds", be.localIds)
                    tasks.put("remark", be.remark)
                    tasks.put("remark1", be.remark1)
                    tasks.put("remark2", be.remark2)
                    tasks.put("remark3", be.remark3)
                    tasks.put("remark4", be.remark4)
                    tasks.put("remark5", be.remark5)
                    tasks.put("remark6", be.remark6)
                    tasks.put("remark7", be.remark7)
                    tasks.put("remark8", be.remark8)
                    tasks.put("updateState", App.getDBcApplication().getOneSendRepeatNoteDetailUpdatestate(userId, it.key, bean.titleId, be.id, true))
                    array1.put(tasks)
                }


            } catch (e: JSONException) {
                e.printStackTrace()
            }
        }

        data.put("timetable", array)
        data1.put("timetable", array1)
        val params = RequestParams()
        params.addBodyParameter("data", data.toString())
        params.addBodyParameter("data1", data1.toString())
        HttpUtils(5000).send(HttpRequest.HttpMethod.POST, URLConstants.发起方任务同步, params, object : RequestCallBack<String>() {
            override fun onSuccess(responseInfo: ResponseInfo<String>) {
                if (!TextUtils.isEmpty(responseInfo.result)) {
                    try {
                        val gson = Gson()
                        val synBean = gson.fromJson(responseInfo.result, TaskSynBean::class.java)
                        if (synBean.status == 0) {
                            val listBeanList = synBean.list
                            if (listBeanList != null) {
                                for (tDeListBean in listBeanList) {
                                    when {
                                        tDeListBean.dataState == 1 -> //新增
                                            when {
                                                tDeListBean.state == 0 -> {//成功
                                                    //修改id和状态值
                                                    App.getDBcApplication().updateSendRepeatNoteTitleId(tDeListBean.id, tDeListBean.newId, userId)
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.newId, userId, 0, true)
                                                }
                                                tDeListBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                    //更改状态为1
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, 1, true)
                                                tDeListBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, -1, true)
                                            }
                                        tDeListBean.dataState == 2 -> //修改
                                            when {
                                                tDeListBean.state == 0 -> //成功
                                                    //修改该id状态值
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, 0, true)
                                                tDeListBean.state == 1 -> //失败
                                                    //更改状态为2
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, 2, true)
                                                tDeListBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, -1, true)
                                            }
                                        tDeListBean.dataState == 3 -> //删除
                                            when {
                                                tDeListBean.state == 0 -> //成功
                                                    //删除该id的清单
                                                    App.getDBcApplication().deleteSendRepeatNoteData1(tDeListBean.id)
                                                tDeListBean.state == 1 -> //失败
                                                    //更改状态为3
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, 3, true)
                                                tDeListBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteTitleState(tDeListBean.id, userId, -1, true)
                                            }
                                    }
                                }
                            }

                            val listBeans = synBean.list2
                            if (listBeans != null) {
                                for (listBean in listBeans) {
                                    when {
                                        listBean.dataState == 1 -> //新增
                                            when {
                                                listBean.state == 0 -> {//成功
                                                    //修改id和状态值
                                                    App.getDBcApplication().updateSendRepeatNoteDetailId(listBean.id, listBean.newId, userId)
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.newId, userId, 0)
                                                }
                                                listBean.state == 1 -> //失败  可以不操作,但是避免意外
                                                    //更改状态为1
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, 1)
                                                listBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, -1)
                                            }
                                        listBean.dataState == 2 -> //修改
                                            when {
                                                listBean.state == 0 -> //成功
                                                    //修改该id状态值
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, 0)
                                                listBean.state == 1 -> //失败
                                                    //更改状态为2
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, 2)
                                                listBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, -1)
                                            }
                                        listBean.dataState == 3 -> //删除
                                            when {
                                                listBean.state == 0 -> //成功
                                                    //删除该id的清单
                                                    App.getDBcApplication().deleteSendRepeatNoteDetails(listBean.id, userId)
                                                listBean.state == 1 -> //失败
                                                    //更改状态为3
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, 3)
                                                listBean.state == 2 -> //异常
                                                    App.getDBcApplication().updateSendRepeatNoteDetailState(listBean.id, userId, -1)
                                            }
                                    }
                                }
                            }
                            Toast.makeText(this@SelectionFirendActivity, "分享成功", Toast.LENGTH_SHORT).show()
                        } else {
                            Toast.makeText(this@SelectionFirendActivity, "网络异常,分享失败", Toast.LENGTH_SHORT).show()
                        }
                    } catch (e: JsonSyntaxException) {
                        e.printStackTrace()
                        Toast.makeText(this@SelectionFirendActivity, "网络异常,分享失败", Toast.LENGTH_SHORT).show()
                    }

                } else {
                    Toast.makeText(this@SelectionFirendActivity, "网络异常,分享失败", Toast.LENGTH_SHORT).show()
                }
                loaders.dismiss()
                onBackPressed()
            }

            override fun onFailure(e: HttpException, s: String) {
                Log.e("TAG", s)
                Toast.makeText(this@SelectionFirendActivity, "网络异常,分享失败", Toast.LENGTH_SHORT).show()
                loaders.dismiss()
            }
        })

    }


    private fun synDataRepeat(puId: Int, pname: String?) {
        try {
            val beans = App.getDBcApplication().getCalenderNoteDetailData(userId, repeatBean.repSourceDesc, true)
            val data = JSONObject()
            val data1 = JSONObject()
            val array = JSONArray()
            val array1 = JSONArray()
            val task = JSONObject()

            task.put("id", repeatBean.repID)
            task.put("uid", userId)
            task.put("ctype", 1)
            task.put("uname", share.getString(ShareFile.USERNAME, ""))
            task.put("pname", pname)
            task.put("ptype", 0)
            task.put("titleImg", share.getString(ShareFile.USERPHOTOPATH, ""))
            task.put("puId", puId)
            task.put("pdeleState", 0)
            task.put("content", repeatBean.repContent)
            task.put("cdate", "")
            task.put("ctime", repeatBean.repTime)
            task.put("repInStable", repeatBean.repInSTable)
            task.put("repType", repeatBean.repType)
            task.put("repTypeParameter", repeatBean.repTypeParameter.replace("\"", ""))
            task.put("cisAlarm", repeatBean.repIsAlarm)
            task.put("cbeforTime", repeatBean.repBeforeTime)
            task.put("calarmSound", repeatBean.repRingCode)
            task.put("calarmSoundDesc", repeatBean.repRingDesc)
            task.put("cdisplayAlarm", repeatBean.repDisplayTime)
            task.put("cpostpone", 0)
            task.put("cimportant", repeatBean.repIsImportant)
            task.put("cisEnd", 0)
            task.put("pIsEnd", 0)
            task.put("styles", repeatBean.repSourceDescSpare)
            task.put("cisDown",1)
            task.put("ccolorType", 0)
            task.put("createTime", repeatBean.repCreateTime)
            task.put("changTime",repeatBean.repCreateTime)
            task.put("titleId", repeatBean.repSourceDesc)
            task.put("remark","")
            task.put("remark1", repeatBean.remark1)
            task.put("remark2", repeatBean.remark2)
            task.put("remark3", "")
            task.put("remark4", "")
            task.put("remark5", "")
            task.put("remark6", "")
            task.put("updateState", "1")
            array.put(task)

            data.put("timetable", array)

            for (be in beans) {
                val tasks = JSONObject()
                tasks.put("id", be.id)
                tasks.put("uid", userId)
                tasks.put("puId", puId)
                tasks.put("ctype", 1)
                tasks.put("titleId", be.titleId)
                tasks.put("titles", be.titles)
                tasks.put("contents", be.contents)
                tasks.put("changeTime", be.changeTime)
                tasks.put("orderId", be.orderId)
                tasks.put("imgPath", "")
                tasks.put("imgUrl", "")
                tasks.put("createTime", be.createTime)
                tasks.put("ltype", be.ltype)
                tasks.put("style", be.style)
                tasks.put("endstate", be.endstate)
                tasks.put("nums", "")
                tasks.put("cpath", "")
                tasks.put("curl", "")
                tasks.put("shareUrl", "")
                tasks.put("sdesc", "")
                tasks.put("localIds", be.localIds)
                tasks.put("remark", "")
                tasks.put("remark1", "")
                tasks.put("remark2", "")
                tasks.put("remark3", "")
                tasks.put("remark4", "")
                tasks.put("remark5", "")
                tasks.put("remark6", "")
                tasks.put("remark7", "")
                tasks.put("remark8", "")
                tasks.put("updateState", "1")
                array1.put(tasks)
            }

            data1.put("timetable", array1)

            val params = RequestParams()
            params.addBodyParameter("data", data.toString())
            params.addBodyParameter("data1", data1.toString())
            HttpUtils(5000).send(HttpRequest.HttpMethod.POST, URLConstants.发起方任务同步, params, object : RequestCallBack<String>() {
                override fun onSuccess(responseInfo: ResponseInfo<String>) {
                }

                override fun onFailure(e: HttpException, s: String) {
                    Log.e("TAG", s)
                }
            })

        } catch (e: JSONException) {
            e.printStackTrace()
        }

    }

    private val progressUtil = ProgressUtil()
    private fun upLoadData() {
        progressUtil.ShowProgress(this, true, true, "同步数据中...")
        try {
            val upList = App.getDBcApplication().queryAllSchData(-1, 0, 0)
            val jsonarray = JSONArray()
            val jsonobject = JSONObject()
            upList.forEach {
                if (it[ScheduleTable.schSourceDesc].equals(titleid)) {
                    val jsonobject1 = JSONObject()
                    jsonobject1.put("tempId", it[ScheduleTable.schID])
                    jsonobject1.put("cId", it[ScheduleTable.schID])
                    jsonobject1.put("cRecommendId", it[ScheduleTable.schcRecommendId])
                    jsonobject1.put("cUid", userId)
                    jsonobject1.put("cContent", it[ScheduleTable.schContent])
                    jsonobject1.put("cDate", it[ScheduleTable.schDate])
                    jsonobject1.put("cTime", it[ScheduleTable.schTime])
                    jsonobject1.put("cIsAlarm", it[ScheduleTable.schIsAlarm])
                    jsonobject1.put("cBeforTime", it[ScheduleTable.schBeforeTime])
                    jsonobject1.put("cDisplayAlarm", it[ScheduleTable.schDisplayTime])
                    jsonobject1.put("cPostpone", it[ScheduleTable.schIsPostpone])
                    jsonobject1.put("cImportant", it[ScheduleTable.schIsImportant])
                    jsonobject1.put("cColorType", it[ScheduleTable.schColorType])
                    jsonobject1.put("cIsEnd", it[ScheduleTable.schIsEnd])
                    jsonobject1.put("cCreateTime", it[ScheduleTable.schCreateTime])
                    jsonobject1.put("cTags", it[ScheduleTable.schTags])
                    jsonobject1.put("cType", it[ScheduleTable.schSourceType])
                    jsonobject1.put("cTypeDesc", it[ScheduleTable.schSourceDesc])
                    jsonobject1.put("cTypeSpare", it[ScheduleTable.schSourceDescSpare])
                    jsonobject1.put("cRepeatId", it[ScheduleTable.schRepeatID])
                    jsonobject1.put("cRepeatDate", it[ScheduleTable.schRepeatDate])
                    jsonobject1.put("cUpdateTime", it[ScheduleTable.schUpdateTime])
                    jsonobject1.put("cOpenState", it[ScheduleTable.schOpenState])
                    jsonobject1.put("cRecommendName", it[ScheduleTable.schcRecommendName])
                    jsonobject1.put("updateState", it[ScheduleTable.schUpdateState])
                    jsonobject1.put("cAlarmSoundDesc", it[ScheduleTable.schRingDesc])
                    jsonobject1.put("cAlarmSound", it[ScheduleTable.schRingCode])
                    jsonobject1.put("schRead", it[ScheduleTable.schRead])
                    jsonobject1.put("attentionid", it[ScheduleTable.schAID])
                    jsonobject1.put("aType", it[ScheduleTable.schAType])
                    jsonobject1.put("webUrl", it[ScheduleTable.schWebURL])
                    jsonobject1.put("imgPath", it[ScheduleTable.schImagePath])
                    jsonobject1.put("cSchRepeatLink", it[ScheduleTable.schRepeatLink])
                    jsonobject1.put("pIsEnd", it[ScheduleTable.schIsEnd])
                    jsonobject1.put("remark", it[ScheduleTable.schRemark1])
                    jsonobject1.put("remark1", it[ScheduleTable.schRemark2])
                    jsonobject1.put("remark2", it[ScheduleTable.schRemark3])
                    jsonobject1.put("remark4", it[ScheduleTable.schRemark4])
                    jsonobject1.put("remark5", it[ScheduleTable.schRemark5])
                    jsonobject1.put("remark7", it[ScheduleTable.schRemark7])
                    jsonobject1.put("remark10", it[ScheduleTable.schRemark10])
                    jsonobject1.put("remark11", it[ScheduleTable.schRemark11])
                    jsonobject1.put("remark12", it[ScheduleTable.schRemark12])
                    jsonarray.put(jsonobject1)
                }
            }
            jsonobject.put("data", jsonarray)
            val schjson = jsonobject.toString()
            var schuppath = ""
            if (share.getString(this, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0") == "1") {
                schuppath = URLConstants.同步数据接口新
            } else if (share.getString(this, ShareFile.USERFILE, ShareFile.UPLOADTYPE, "0") == "0") {
                schuppath = URLConstants.同步数据接口2新
            }

            val params = RequestParams()
            params.addBodyParameter("json", schjson)
            HttpUtils(5000).send(HttpRequest.HttpMethod.POST, schuppath, params, object : RequestCallBack<String>() {
                override fun onSuccess(responseInfo: ResponseInfo<String>) {
                    if (!TextUtils.isEmpty(responseInfo.result)) {
                        val gson = Gson()
                        val UpNew = gson.fromJson(responseInfo.result, UpNew::class.java)
                        val listBeanList: List<UpNew.ListBean>?
                        if (UpNew.status == 0) {
                            listBeanList = UpNew.list
                            if (listBeanList != null) {
                                if (listBeanList.isNotEmpty()) {
                                    listBeanList.forEach {
                                        when {
                                            it.dataState == 1 -> {//新增
                                                if (schID == it.id) {
                                                    schID = it.calendId.toString() + ""
                                                }
                                                //新增成功就修改id和状态
                                                when {
                                                    it.state == 0 -> {//成功
                                                        App.getDBcApplication().UpdateSchID(Integer.parseInt(it.id), it.calendId)
                                                        App.getDBcApplication().updateUpdateState(it.calendId)
                                                        App.getDBcApplication().UpdateClockSchID(it.id, it.calendId.toString() + "")
                                                        schID = it.calendId.toString() + ""
                                                    }
                                                    it.state == 1 -> {//失败
                                                        com.mission.schedule.cutimage.Log.e("UPLOADCALENDER", it.calendId.toString() + ":FAILED")
                                                        App.getDBcApplication().updateUpdateStateFaild(it.calendId, 1)
                                                    }
                                                    it.state == 2 -> App.getDBcApplication().updateUpdateStateFaild(it.calendId, -1)
                                                }
                                            }
                                            it.dataState == 3 -> {//删除
                                                //删除成功删除数据
                                                when {
                                                    it.state == 0 -> App.getDBcApplication().deleteScheduleData(it.calendId)
                                                    it.state == 1 -> {
                                                        com.mission.schedule.cutimage.Log.e("UPLOADCALENDER", it.calendId.toString() + ":FAILED")
                                                        App.getDBcApplication().updateUpdateStateFaild(it.calendId, 3)
                                                    }
                                                    it.state == 2 -> App.getDBcApplication().updateUpdateStateFaild(it.calendId, -1)
                                                }
                                                App.getDBcApplication().deleteSch(it.calendId)
                                            }
                                            it.dataState == 2 -> //修改
                                                //修改成功修改状态
                                                when {
                                                    it.state == 0 -> App.getDBcApplication().updateUpdateState(it.calendId)
                                                    it.state == 1 -> {
                                                        com.mission.schedule.cutimage.Log.e("UPLOADCALENDER", it.calendId.toString() + ":FAILED")
                                                        App.getDBcApplication().updateUpdateStateFaild(it.calendId, 2)
                                                    }
                                                    it.state == 2 -> App.getDBcApplication().updateUpdateStateFaild(it.calendId, -1)
                                                }
                                        }
                                        share.putString(application, ShareFile.USERFILE, ShareFile.DOWNREPTIME,
                                                it.downTime.replace("T", " "))
                                    }
                                }
                            }
                        }
                    }
                    progressUtil.dismiss()
                }

                override fun onFailure(e: HttpException, s: String) {
                    progressUtil.dismiss()
                    Toast.makeText(this@SelectionFirendActivity, "同步失败!", Toast.LENGTH_SHORT).show()
                }
            })

        } catch (e: Exception) {
            e.printStackTrace()
            progressUtil.dismiss()
            Toast.makeText(this@SelectionFirendActivity, "同步失败!", Toast.LENGTH_SHORT).show()
        }

    }

}